<?php
namespace app\admin\controller;



class Goods extends Base
{
    private $m="goods";
    protected function _initialize()
    {
        $top_cate_lists=model("cate")->where("up_id",0)->order("sort")->select();
        $list=[];
        foreach ($top_cate_lists as $item){
            $list[]=$item;
            $id=$item['id'];
            $sublist=model("cate")->where("up_id",$id)->order("sort")->select();
            foreach ($sublist as $subitem){
                $subitem['name']="├".$subitem['name'];
                $list[]=$subitem;
            }
        }
        $this->assign("catelist",$list);
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    public function lists(){
        $cate_id=input("cate_id");
        $where=[];
        $where["delete_time"]=['null',""];
        if(!empty($cate_id)){
            $where['cate_id']=$cate_id;
        }
        $list = model($this->m)->where($where)->order("sort asc,id asc")->paginate(10,null,['query'=>['cate_id'=>$cate_id]]);
        $this->assign("list",$list);
        return view();
    }

    public function edit(){
        $id=input("id");
        $oldnumber=0;
        if(!empty($id)){
            $info=model($this->m)->where("id",$id)->find();
            $this->assign("info",$info);
            $oldnumber=$info['number'];
        }
        if(request()->isPost()){
            $data=$this->autodata();
            if(!empty($data['tags_form'])){
                $data['tags']=implode(",",$data['tags_form']);
            }
            $id=input("id");
            if(empty($id)){
                model($this->m)->allowField(true)->save($data);
                $goods_id=model($this->m)->id;
            }else{
                model($this->m)->allowField(true)->save($data,["id"=>$id]);
                $goods_id=$id;
            }
            inventory($goods_id,$data['cnumber']-$oldnumber,"管理员变更");
            $this->success("编辑成功","/admin/{$this->m}/lists");
        }
        return view();
    }

    public function del(){
        $id=input("id");
        $mod=model($this->m)->where("id",$id)->find();
        if(empty($mod)){
            $this->error("数据不存在");
        }
        $mod->save(['delete_time'=>now()]);
        $this->success("删除成功","/admin/{$this->m}/lists");
    }
}
